<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>登录页面配置</span>
      </div>
      
      <!-- 系统标题配置 -->
      <el-form ref="titleForm" :model="titleForm" label-width="120px" style="margin-bottom: 20px;">
        <el-form-item label="系统标题">
          <el-input v-model="titleForm.title" placeholder="请输入系统标题" style="width: 300px;"></el-input>
          <el-button @click="saveTitle" type="primary" style="margin-left: 10px;">保存标题</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>

      <!-- 背景图片配置 -->
      <el-form ref="bgForm" :model="bgForm" label-width="120px">
        <el-form-item label="登录背景图片">
          <div class="background-config">
            <el-upload
              class="background-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="handleBackgroundUpload"
              accept="image/*">
              <img v-if="backgroundImageUrl" :src="backgroundImageUrl" class="background-preview" />
              <i v-else class="el-icon-plus background-uploader-icon"></i>
            </el-upload>
            
            <div class="upload-info">
              <div class="upload-tips">
                <p><strong>上传要求：</strong></p>
                <p>• 推荐尺寸：1920x1080px</p>
                <p>• 支持格式：jpg、png</p>
                <p>• 文件大小：不超过2MB</p>
              </div>
              
              <div class="upload-actions">
                <el-button @click="saveBackground" type="primary" :disabled="!backgroundImageUrl">保存背景</el-button>
                <el-button @click="clearBackground" type="danger" v-if="backgroundImageUrl">清除图片</el-button>
                <el-button @click="previewLogin" type="success">预览登录页</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getConfigKey } from "@/api/system/config"
import { addConfig, updateConfig, getConfig } from "@/api/system/config"
import { uploadFileInfo, getFileDisplayUrl } from "@/api/system/fileinfo"

export default {
  name: "LoginConfig",
  data() {
    return {
      titleForm: {
        title: ''
      },
      bgForm: {
        backgroundImage: ''
      },
      backgroundImageUrl: '',
      titleConfigId: null,
      bgConfigId: null
    }
  },
  created() {
    this.loadCurrentConfig()
  },
  methods: {
    // 加载当前配置
    async loadCurrentConfig() {
      try {
        // 加载标题配置
        const titleResponse = await getConfigKey("sys.index.title")
        if (titleResponse.msg) {
          this.titleForm.title = titleResponse.msg
        }

        // 加载背景图片配置
        const bgResponse = await getConfigKey("sys.login.backgroundImage")
        if (bgResponse.msg && bgResponse.msg.trim()) {
          const fileId = bgResponse.msg.trim()
          if (/^\d+$/.test(fileId)) {
            // 如果是数字，说明是文件ID
            this.bgForm.backgroundImage = fileId
            this.backgroundImageUrl = getFileDisplayUrl(fileId)
          } else {
            // 如果不是，可能是旧的base64格式
            this.bgForm.backgroundImage = bgResponse.msg
            this.backgroundImageUrl = bgResponse.msg
          }
        }
      } catch (error) {
        console.log('加载配置失败:', error)
      }
    },

    // 保存标题
    async saveTitle() {
      if (!this.titleForm.title.trim()) {
        this.$modal.msgError('请输入系统标题')
        return
      }

      try {
        const configData = {
          configName: '系统登录标题',
          configKey: 'sys.index.title',
          configValue: this.titleForm.title,
          configType: 'N',
          remark: '系统登录页面显示的标题'
        }

        if (this.titleConfigId) {
          configData.configId = this.titleConfigId
          await updateConfig(configData)
        } else {
          await addConfig(configData)
        }

        this.$modal.msgSuccess('标题保存成功')
        this.loadCurrentConfig()
      } catch (error) {
        this.$modal.msgError('标题保存失败')
      }
    },

    // 保存背景图片
    async saveBackground() {
      if (!this.backgroundImageUrl) {
        this.$modal.msgError('请先上传背景图片')
        return
      }

      try {
        const configData = {
          configName: '登录页背景图片',
          configKey: 'sys.login.backgroundImage',
          configValue: this.bgForm.backgroundImage, // 这里存储的是文件ID
          configType: 'N',
          remark: '登录页面背景图片的文件ID'
        }

        if (this.bgConfigId) {
          configData.configId = this.bgConfigId
          await updateConfig(configData)
        } else {
          await addConfig(configData)
        }

        this.$modal.msgSuccess('背景图片保存成功')
        this.loadCurrentConfig()
      } catch (error) {
        this.$modal.msgError('背景图片保存失败')
      }
    },

    // 处理背景图片上传
    handleBackgroundUpload(file) {
      // 文件大小限制（2MB）
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$modal.msgError('上传图片大小不能超过 2MB!')
        return false
      }
      
      // 文件类型限制
      const isImage = file.type.indexOf('image/') === 0
      if (!isImage) {
        this.$modal.msgError('上传文件只能是图片格式!')
        return false
      }
      
      // 上传文件到服务器
      const formData = new FormData()
      formData.append('file', file)
      
      uploadFileInfo(formData).then(response => {
        if (response.code === 200) {
          const fileId = response.fileId
          if (fileId) {
            this.bgForm.backgroundImage = fileId.toString()
            this.backgroundImageUrl = getFileDisplayUrl(fileId)
            this.$modal.msgSuccess('图片上传成功')
          } else {
            this.$modal.msgError('获取文件ID失败')
          }
        } else {
          this.$modal.msgError('图片上传失败：' + response.msg)
        }
      }).catch(error => {
        console.error('上传失败:', error)
        this.$modal.msgError('图片上传失败')
      })
      
      return false // 阻止自动上传
    },

    // 清除背景图片
    clearBackground() {
      this.bgForm.backgroundImage = ''
      this.backgroundImageUrl = ''
    },

    // 预览登录页
    previewLogin() {
      // 打开新窗口预览登录页
      const routeData = this.$router.resolve({ path: '/login' })
      window.open(routeData.href, '_blank')
    }
  }
}
</script>

<style scoped>
.background-config {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.background-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;
}

.background-uploader:hover {
  border-color: #409EFF;
}

.background-uploader-icon {
  font-size: 36px;
  color: #8c939d;
}

.background-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-info {
  flex: 1;
}

.upload-tips {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.upload-tips p {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}

.upload-actions {
  display: flex;
  gap: 10px;
}

.box-card {
  margin: 20px;
}
</style>